package dao.impl;

import dao.UserDao;
import pojo.User;

import java.sql.*;
import java.util.ArrayList;
import java.util.List;

public class UserDaoImpl implements UserDao {
    @Override
    public List<User> findAll() {
        List<User> users = new ArrayList<>();
        //jdbc 查询数据库操作
        Connection conn = null;
        PreparedStatement preparedStatement = null;
        ResultSet resultSet = null;


        //1、 加载驱动
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");

            //2、获取连接
            conn = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/jdbc?characterEncoding=utf-8",
                    "root","120513");

            //3、编写sql语句
            String sql = "select * from user";

            //4、预处理sql  .var
            preparedStatement = conn.prepareStatement(sql);

            //5、如果有参数，设置参数

            //6、执行sql语句
            resultSet = preparedStatement.executeQuery();

            // 7、如果是查询就遍历结果/如果是增删改 判断是否成功
            while (resultSet.next()) {
                User u = new User();
                u.setId(resultSet.getInt(1));
                u.setUsername(resultSet.getString(2));
                u.setPassword(resultSet.getString(3));
                users.add(u);
                return users;
            }

        } catch (ClassNotFoundException e) {
            throw new RuntimeException(e);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        } finally{
            // 8、关闭资源
            try {
                // NullPointException
                if(resultSet != null){
                    resultSet.close();
                }
                if(preparedStatement != null){
                    preparedStatement.close();
                }
                if(conn != null){
                    conn.close();
                }
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }

        }



        return null;
    }
}
